package com.weixin.mp.controller;

import com.weixin.mp.entity.User;
import com.weixin.mp.service.UserService;
import com.weixin.mp.utils.JwtUtils;
import com.weixin.mp.utils.OssUtils;
import com.weixin.mp.vo.Result;
import com.weixin.mp.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private OssUtils ossUtils;
    
    /**
     * 微信小程序登录
     * @param code 微信授权code
     * @return 登录结果
     */
    @PostMapping("/wxLogin")
    public Result wxLogin(@RequestParam(value = "code", required = true) String code) {
        log.info("收到微信登录请求，code: {}", code);
        
        if (!StringUtils.hasText(code)) {
            log.error("微信登录失败：code为空");
            return Result.error("code不能为空");
        }
        
        try {
            String token = userService.wxLogin(code);
            log.info("微信登录成功，生成token: {}", token);
            
            if (token == null) {
                log.error("微信登录失败：token生成失败");
                return Result.error("登录失败");
            }
            
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            
            return Result.ok(map);
        } catch (Exception e) {
            log.error("微信登录异常", e);
            return Result.error("登录异常: " + e.getMessage());
        }
    }
    
    /**
     * 更新用户信息
     * @param userInfoVO 用户信息
     * @return 更新结果
     */
    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestBody UserInfoVO userInfoVO, HttpServletRequest request) {
        // 获取token中的openid
        String token = request.getHeader(JwtUtils.getHeader());
        String openid = JwtUtils.getOpenidFromToken(token);
        
        if (openid == null) {
            return Result.error("用户未登录");
        }
        
        boolean result = userService.updateUserInfo(
            openid,
            userInfoVO.getNickname(),
            userInfoVO.getAvatarUrl(),
            userInfoVO.getGender(),
            userInfoVO.getCountry(),
            userInfoVO.getProvince(),
            userInfoVO.getCity()
        );
        
        if (result) {
            return Result.ok();
        } else {
            return Result.error("更新用户信息失败");
        }
    }
    
    /**
     * 保存用户手机号
     * @param phone 手机号
     * @return 保存结果
     */
    @PostMapping("/saveUserPhone")
    public Result saveUserPhone(@RequestParam String phone, HttpServletRequest request) {
        // 获取token中的openid
        String token = request.getHeader(JwtUtils.getHeader());
        String openid = JwtUtils.getOpenidFromToken(token);
        
        if (openid == null) {
            return Result.error("用户未登录");
        }
        
        boolean result = userService.saveUserPhone(openid, phone);
        
        if (result) {
            return Result.ok();
        } else {
            return Result.error("保存手机号失败");
        }
    }
    
    /**
     * 获取用户信息
     * @return 用户信息
     */
    @GetMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        // 获取token中的openid
        String token = request.getHeader(JwtUtils.getHeader());
        String openid = JwtUtils.getOpenidFromToken(token);
        
        if (openid == null) {
            return Result.error("用户未登录");
        }
        
        User user = userService.getUserByOpenid(openid);
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        return Result.ok(user);
    }
    
    /**
     * 获取用户手机号（适用于新版微信API）
     * @param code 手机号获取凭证
     * @return 手机号信息
     */
    @PostMapping("/getPhoneNumber")
    public Result getPhoneNumber(@RequestParam(required = true) String code, HttpServletRequest request) {
        log.info("收到获取手机号请求，code: {}, 请求方式: {}, Content-Type: {}", 
                code, 
                request.getMethod(), 
                request.getContentType());
        
        // 打印所有请求头
        java.util.Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            log.info("请求头 {}: {}", headerName, request.getHeader(headerName));
        }
        
        if (!StringUtils.hasText(code)) {
            log.error("获取手机号失败：code为空");
            return Result.error("code不能为空");
        }
        
        try {
            // 获取token中的openid
            String token = request.getHeader(JwtUtils.getHeader());
            if (token == null || token.isEmpty()) {
                log.error("获取手机号失败：未提供token");
                return Result.error("未提供有效的token");
            }
            
            log.info("解析token: {}", token);
            String openid = JwtUtils.getOpenidFromToken(token);
            
            if (openid == null) {
                log.error("获取手机号失败：用户未登录");
                return Result.error("用户未登录");
            }
            
            // 调用服务获取手机号
            Map<String, Object> phoneInfo = userService.getPhoneNumber(openid, code);
            if (phoneInfo == null) {
                log.error("获取手机号失败");
                return Result.error("获取手机号失败");
            }
            
            log.info("获取手机号成功: {}", phoneInfo);
            return Result.ok(phoneInfo);
        } catch (Exception e) {
            log.error("获取手机号异常", e);
            return Result.error("获取手机号异常: " + e.getMessage());
        }
    }
    
    /**
     * 上传头像
     * @param file 头像文件
     * @param request HTTP请求
     * @return 上传结果
     */
    @PostMapping("/uploadAvatar")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        log.info("收到上传头像请求，文件大小: {} bytes", file.getSize());
        
        if (file.isEmpty()) {
            log.error("上传头像失败：文件为空");
            return Result.error("请选择要上传的文件");
        }
        
        try {
            // 获取token中的openid
            String token = request.getHeader(JwtUtils.getHeader());
            String openid = JwtUtils.getOpenidFromToken(token);
            
            if (openid == null) {
                log.error("上传头像失败：用户未登录");
                return Result.error("用户未登录");
            }
            
            // 上传文件到OSS
            String avatarUrl = ossUtils.uploadAvatar(file);
            log.info("上传头像到OSS成功，URL: {}", avatarUrl);
            
            // 更新用户头像
            boolean result = userService.updateUserAvatar(openid, avatarUrl);
            
            if (result) {
                Map<String, Object> data = new HashMap<>();
                data.put("avatarUrl", avatarUrl);
                return Result.ok(data);
            } else {
                return Result.error("更新用户头像失败");
            }
        } catch (Exception e) {
            log.error("上传头像异常", e);
            return Result.error("上传头像异常: " + e.getMessage());
        }
    }
} 